﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
using System.Security.Policy;
using System.Threading.Tasks;
using System.Xml.Linq;
using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Model.FromBody;
using CoreShop.Model.UI;
using CoreShop.Repository;
using Newtonsoft.Json;
using SqlSugar;
using static CoreShop.Library.GlobalEnumVars;


namespace CoreShop.Services
{
    /// <summary>
    /// 接口实现
    /// </summary>
    public class sysuserServices : Repository<sysuser>, IsysuserServices
    {
        #region 实现重写增删改查操作==========================================================

        /// <summary>
        /// 重写异步插入方法
        /// </summary>
        /// <param name="entity">实体数据</param>
        /// <returns></returns>
        public bool InsertAsync(sysuser entity)
        {
            return base.Change<sysuser>().Insert(entity);
        }
        public bool InsertOrUpdate(List<sysuser> entity)
        {
            return base.InsertOrUpdate(entity);
        }
        /// <summary>
        /// 重写异步更新方法方法
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool UpdateAsync(sysuser entity)
        {
            return base.Change<sysuser>().Update(a => new sysuser()
            {
                corpId = entity.corpId,
                storeId = entity.storeId,
                userName = entity.userName,
                phone = entity.phone,
                passWord = entity.passWord,
                nickName = entity.nickName,
                userType = entity.userType,
                sex = entity.sex,
                email = entity.email,
                trueName = entity.trueName,
                organizationId = entity.organizationId,
                state = entity.state,
                deleted = entity.deleted,
                registerFlag = entity.registerFlag
            }, a => a.id == entity.id);
        }

        /// <summary>
        /// 重写异步更新方法方法
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool UpdateAsync(List<sysuser> entity)
        {
            bool returnKey = true;
            foreach (var item in entity)
            {
                returnKey = base.Change<sysuser>().Update(a => new sysuser()
                {
                    corpId = item.corpId,
                    storeId = item.storeId,
                    userName = item.userName,
                    phone = item.phone,
                    passWord = item.passWord,
                    nickName = item.nickName,
                    userType = item.userType,
                    sex = item.sex,
                    email = item.email,
                    trueName = item.trueName,
                    organizationId = item.organizationId,
                    state = item.state,
                    deleted = item.deleted,
                    registerFlag = item.registerFlag
                }, a => a.id == item.id);
            }
            return returnKey;
        }

        /// <summary>
        /// 重写删除指定ID的数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DeleteByIdAsync(long id)
        {
            return base.Change<sysuser>().Update(a => new sysuser()
            {
                deleted = true
            }, a => a.id == id);
        }

        /// <summary>
        /// 重写删除指定ID集合的数据(批量删除)
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public bool DeleteByIdsAsync(int[] ids)
        {
            bool returnKey = true;
            foreach (int id in ids)
            {
                returnKey = base.Change<sysuser>().Update(a => new sysuser()
                {
                    deleted = true
                }, a => a.id == id);
            }
            return returnKey;
        }

        #endregion

        #region 获取缓存的所有数据==========================================================

        /// <summary>
        /// 获取缓存的所有数据
        /// </summary>
        /// <returns></returns>
        public List<sysuser> GetCaChe()
        {
            return base.GetList();
        }

        #endregion

        #region 根据条件查询分页数据
        /// <summary>
        /// 根据条件查询分页数据
        /// </summary>
        /// <param name="count"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="sName"></param>
        /// <returns></returns>
        public List<sysuser> QueryPageAsync(ref int count, int? pageIndex, int? pageSize, string sName)
        {
            List<sysuser> lst = new List<sysuser>();
            var where = Expressionable.Create<sysuser>();
            where = where.And(a => a.deleted == false);
            if (!string.IsNullOrEmpty(sName))
            {
                where = where.And(a => a.userName.Contains(sName))
                    .Or(a => a.nickName.Contains(sName)).Or(a => a.trueName.Contains(sName));
            }
            if (pageIndex >= 1 && pageSize > 0)
            {
                lst = base.AsQueryable().WhereIF(true, where.ToExpression())
                    .ToPageList((int)pageIndex, (int)pageSize, ref count)
                    .OrderBy(a => a.id).ToList();
            }
            else
            {
                lst = base.AsQueryable().WhereIF(true, where.ToExpression()).OrderBy(a => a.id).ToList();
            }

            return lst;
        }
        #endregion

        public sysuser QueryByNameAsync(string name, string pwd, string adminPwd)
        {
            var where = Expressionable.Create<sysuser>();
            where = where.And(a => a.userName == name || a.phone == name);
            if (pwd != adminPwd) where = where.And(a => a.passWord == pwd);
            return base.Change<sysuser>().GetFirst(where.ToExpression());
        }

        /// <summary>
        /// 用户后台登录保存到本地
        /// </summary>
        /// <returns></returns>
        public bool SetLoginData(ref sysuser sysuser, LoginBody loginBody, corecmsstore store)
        {
            string token = loginBody.access_token;
            long posUserId = loginBody.userInfo.posUserId;
            var userSvr = new sysuserServices();
            if (sysuser == null) sysuser = userSvr.GetById(posUserId);
            if (sysuser == null) sysuser = new sysuser();               
            sysuser.id = posUserId;
            sysuser.state = 0;
            sysuser.state = 0;
            sysuser.nickName = loginBody.userInfo.userCode;
            sysuser.userName = loginBody.userInfo.userName;
            sysuser.passWord = Security.Encrypt(loginBody.userInfo.password.Trim());
            sysuser.corpId = loginBody.userInfo.tenantId;
            sysuser.storeId = store.id;
            sysuser.posUserId = posUserId;
            sysuser.phone = loginBody.userInfo.phonenumber;
            sysuser.ccessToken = token;
            sysuser.loginTime = DateTime.Now;
            sysuser.posRoleId = loginBody.userInfo.posRoleId;
            userSvr.InsertOrUpdateAsync(sysuser);
            SetSysroleposAuto(sysuser);

            return true;            
        }

        /// <summary>
        /// 自动添加权限并允许
        /// </summary>
        /// <param name="sysuser"></param>
        public void SetSysroleposAuto(sysuser sysuser)
        {
            try
            {
                var roleposList = new sysroleposServices().AsQueryable().Where(p => p.sysUserId == sysuser.id).ToList();
                if (roleposList.Count == 0)
                {
                    var rmoRoles = new List<sysrolepos>();
                    foreach (string colorName in Enum.GetNames(typeof(GlobalEnumVars.UserRoleType)))
                    {
                        var rmoRole = new sysrolepos();
                        rmoRole.roleId = sysuser.id.ToString() + colorName;
                        rmoRole.sysUserId = sysuser.id;
                        rmoRole.component = colorName;
                        rmoRole.menu_name = EnumHelper.GetEnumDescriptionByKey<GlobalEnumVars.UserRoleType>(colorName);
                        rmoRole.status = true;
                        rmoRole.visible = true;
                        rmoRoles.Add(rmoRole);
                    }
                    new sysroleposServices().InsertOrUpdateAsync(rmoRoles);
                }
            }
            catch (Exception ex) { }
        }

        public bool ClearBaseData(long storeId, sysuser loginUser)
        {
            try
            {
                bool returnValue = new corecmsstoreServices().Delete(p=>p.id != storeId);
                returnValue = new corecmsemployeeServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsexchangeServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsfoodServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsfoodcategoryServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsfooddeskServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsfooddeskcategoryServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsfooddetailfeedServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsfooddetailtaskServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsfoodfeedServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsfoodfeedcategoryServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsfoodorderclassServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsfoodorderingmasterServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsfoodordermasterServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsexchangeServices().Delete(p => p.storeId != storeId);

                var orderIds = new corecmsfoodordermasterServices().GetList().Select(p=>p.orderId).ToList();
                returnValue = new corecmsfoodorderdetailServices().Delete(p => !orderIds.Contains(p.orderId));
                returnValue = new corecmsfoodorderfeedServices().Delete(p => !orderIds.Contains(p.orderId));
                returnValue = new corecmsfoodorderpaymentServices().Delete(p => !orderIds.Contains(p.orderId));
                returnValue = new corecmsfoodordertagServices().Delete(p => !orderIds.Contains(p.orderId));
                returnValue = new corecmsfoodordertaskServices().Delete(p => !orderIds.Contains(p.orderId));

                var orderingIds = new corecmsfoodorderingmasterServices().GetList().Select(p => p.orderId).ToList();
                returnValue = new corecmsfoodorderingServices().Delete(p => !orderingIds.Contains(p.orderId));
                returnValue = new corecmsfoodorderingfeedServices().Delete(p => !orderingIds.Contains(p.orderId));
                returnValue = new corecmsfoodorderingtagServices().Delete(p => !orderingIds.Contains(p.orderId));
                returnValue = new corecmsfoodorderingtaskServices().Delete(p => !orderingIds.Contains(p.orderId));

                returnValue = new corecmsfoodpackServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsfoodpackdetailServices().Delete(p => p.storeId != storeId);                
                returnValue = new corecmsfoodsoldoutServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsfoodspecServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsfoodtagServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsfoodtaskServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsfoodtaskcategoryServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsfoodtotalServices().Delete(p => p.storeId != storeId);
                //returnValue = new corecmsstoremarketServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsuserServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsuserbalanceServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsusercategoryServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsuserdepositrulesServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsusergradeServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsuserpointServices().Delete(p => p.storeId != storeId);
                returnValue = new sysuserServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmspaymentsService().Delete(p => p.storeId != storeId && p.storeId > 0 && p.id > 7);
                returnValue = new corecmsdiscountrulesServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsuserintegralrulesServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsdepartmentService().Delete(p => p.storeId != storeId);
                returnValue = new corecmsdiscountrulesServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsfooddeskfeeServices().Delete(p => p.storeId != storeId);
                returnValue = new corecmsuserintegralrulesServices().Delete(p => p.storeId != storeId);
                returnValue = base.Change<corecmsstoreorganization>().Delete(p => p.storeId != storeId);
                returnValue = new activitymasterServices().Delete(p => p.activityInfoId > 0);
                returnValue = new activitygoodsServices().Delete(p => p.activityInfoId > 0);
                returnValue = new activitygoodsexcludeServices().Delete(p => p.activityInfoId > 0);
                returnValue = new activitylinerespServices().Delete(p => p.activityInfoId > 0);
                returnValue = new activitysortServices().Delete(p => p.activityInfoId > 0);

                returnValue = new sysroleposServices().Delete(p => p.sysUserId != loginUser.id);
                returnValue = new corecmsfoodpriceServices().Delete(p => p.tenantId != loginUser.corpId);
                returnValue = new corecmsfoodbarcodesServices().Delete(p => p.tenantId != loginUser.corpId);
                returnValue = new corecmsfoodunitServices().Delete(p => p.tenantId != loginUser.corpId);
                returnValue = new corecmsordermasterServices().Delete(p => p.id > 0);
                returnValue = new sysrecordentityServices().Delete(p => p.id > 0);
                returnValue = new corecmschgpriceServices().Delete(p => p.chgpriceLineId > 0);

                var foodIds = new corecmsfoodServices().GetList().Select(p => p.id).ToList();
                returnValue = new corecmsfoodprintschemeServices().Delete(p => !foodIds.Contains(p.foodId));
                returnValue = new syssettingServices().Delete(p => p.corpId != loginUser.corpId);
                returnValue = new corecmspaymentsService().Delete(p => p.id > 20);//小于20为固定的支付，不能修改

                var systemsetup = new corecmssystemsetupService().SelectDataFirst();
                if (systemsetup == null) systemsetup = new corecmssystemsetup();
                systemsetup.storeId = storeId;
                systemsetup.sxfMno = "";
                systemsetup.checkTimes = 0;
                string mApiUrl = IniFiles.ReadIniData("WebAPI", "adminApiUrl");
                if (mApiUrl != null) systemsetup.adminApiUrl = mApiUrl;
                mApiUrl = IniFiles.ReadIniData("WebAPI", "corehubUrl");
                if (mApiUrl != null) systemsetup.corehubUrl = mApiUrl;
                mApiUrl = IniFiles.ReadIniData("WebAPI", "carouselUrl");
                if (mApiUrl != null) systemsetup.carouselUrl = mApiUrl;
                new corecmssystemsetupService().InsertOrUpdate(systemsetup);

                new corecmspaymentsService().Change<corecmspayments>().Update(a => new corecmspayments()
                {
                    tenantBalanceTypeId = 0,
                    posUsed = 0,
                    rechargeUsed = 0
                }, a => a.id > 0);

                new corecmspaymentsService().Change<corecmspayments>().Update(a => new corecmspayments()
                {
                    posUsed = 1,
                    rechargeUsed = 1
                }, a => a.id == 1 || a.id == 3 || a.id == 7);

                return true;
            }
            catch
            {

            }
            return false;
        }

    }
}